import re
from django.db.models.sql.constants import *
from django.db.models.fields import AutoField
from django.db.models.sql.query import select_related_descend


AND = 'AND'
OR = 'OR'
OP_MAP = {
        'gte' : '>=',
        'gt' : '>',
        'lte' : '<=',
        'lt' : '<',
}
NEGATED_OP_MAP = {
        'gte' : '<',
        'gt' : '<=',
        'lte' : '>',
        'lt' : '>=',
}
def full_value_update( old, new ):
    for k, v in new.items():
        if old.has_key(k):
            old_v = old[k]
            if isinstance( old_v, dict ) and isinstance( v, dict ):
                if len( old_v ) > 1 or len(v) > 1:
                    raise NotImplementedError
                old[k].update( v )
            else:
                raise Exception("Condition Conflict",k,old[k], v )
        else:
            old[k] = v

def full_update( src, des , connector):
    for k, v in des.items():
        src.setdefault( k , {} )

        if connector == AND:
            #src[k] = full_value_update( src[k], v )
            full_value_update( src[k], v )
        elif connector == OR:
            src_value = src[k] 
            if src_value:
                src[k] = {'$or': [ src_value, v ] }
            else:
                src_value.update( v )
        else:
            raise Exception("Unkown Connector" , connector )


def get_order_dir(field, standard=True):

    col = field
    direction = standard and 1 or -1
    if field[0] == '-':
        col = field[1:]
        direction *= -1

    return col, direction

def get_op(lookup_type, negated=False):

    if negated:
        return NEGATED_OP_MAP.get(lookup_type,'!=')
    else:
        return OP_MAP.get(lookup_type,'==')


class SQLCompiler(object):
    def __init__(self, query, connection, using):
        self.query = query
        self.connection = connection
        self.using = using
        self.quote_cache = {}

        self._join_target = {}
        self._join_tables = [None]


    def get_grouping(self):
        """
        Returns a tuple representing the SQL elements in the "group by" clause.
        """
        result, params = [], []
        if self.query.group_by is not None:
            if len(self.query.model._meta.fields) == len(self.query.select) and \
                self.connection.features.allows_group_by_pk:
                self.query.group_by = [(self.query.model._meta.db_table, self.query.model._meta.pk.column)]

            group_by = self.query.group_by or []
            print 'yyy',group_by

            extra_selects = []
            for extra_select, extra_params in self.query.extra_select.itervalues():
                extra_selects.append(extra_select)
                params.extend(extra_params)
            for col in group_by + self.query.related_select_cols + extra_selects:
                if isinstance(col, (list, tuple)):
                    result.append('%s.%s' % (col[0], col[1]))
                elif hasattr(col, 'as_sql'):
                    raise NotImplementedError, col
                    result.append(col.as_sql(qn))
                else:
                    result.append('(%s)' % str(col))
        return result, params
    def get_from_clause(self):
        """
        Returns a list of strings that are joined together to go after the
        "FROM" part of the query, as well as a list any extra parameters that
        need to be included. Sub-classes, can override this to create a
        from-clause via a "select".

        This should only be called after any SQL construction methods that
        might change the tables we need. This means the select columns and
        ordering must be done first.
        """
        result = []
        first = True
        params = {}
        for alias in self.query.tables:
            if not self.query.alias_refcount.has_key(alias):
                result.append( alias )
                continue
            if not self.query.alias_refcount[alias]:
                #raise str(self.query.tables) + str(self.query.alias_refcount)
                #print str(self.query.tables) + str(self.query.alias_refcount)
                continue
            try:
                name, alias, join_type, lhs, lhs_col, col, nullable = self.query.alias_map[alias]
            except KeyError:
                # Extra tables can end up in self.tables, but not in the
                # alias_map if they aren't in a join. That's OK. We skip them.
                continue
            alias_str = (alias != name and ' %s' % alias or '')
            if join_type and not first:
                #result.append('%s %s%s ON (%s.%s = %s.%s)'
                #        % (join_type, qn(name), alias_str, qn(lhs),
                #           qn2(lhs_col), qn(alias), qn2(col)))
                result.append( name )
                params[ '%s.%s' % (lhs,lhs_col) ] = '%s.%s' % (alias,col )
            else:
                connector = not first and ', ' or ''
                #result.append('%s%s%s' % (connector, qn(name), alias_str))
                result.append( name )
            first = False
        for t in self.query.extra_tables:
            raise NotImplementedError
            alias, unused = self.query.table_alias(t)
            # Only add the alias if it's not already present (the table_alias()
            # calls increments the refcount, so an alias refcount of one means
            # this is the only reference.
            if alias not in self.query.alias_map or self.query.alias_refcount[alias] == 1:
                connector = not first and ', ' or ''
                result.append('%s%s' % (connector, qn(alias)))
                first = False
        return result, params

    def find_ordering_name(self, name, opts, alias=None, default_order=1,
            already_seen=None):
        """
        Returns the table alias (the name might be ambiguous, the alias will
        not be) and column name for ordering by the given 'name' parameter.
        The 'name' is of the form 'field1__field2__...__fieldN'.
        """
        name, order = get_order_dir(name, default_order)
        pieces = name.split(LOOKUP_SEP)
        if not alias:
            alias = self.query.get_initial_alias()
        field, target, opts, joins, last, extra = self.query.setup_joins(pieces,
                opts, alias, False)
        alias = joins[-1]
        col = target.column
        if not field.rel:
            # To avoid inadvertent trimming of a necessary alias, use the
            # refcount to show that we are referencing a non-relation field on
            # the model.
            self.query.ref_alias(alias)

        # Must use left outer joins for nullable fields and their relations.
        self.query.promote_alias_chain(joins,
            self.query.alias_map[joins[0]][JOIN_TYPE] == self.query.LOUTER)

        # If we get to this point and the field is a relation to another model,
        # append the default ordering for that model.
        if field.rel and len(joins) > 1 and opts.ordering:
            # Firstly, avoid infinite loops.
            if not already_seen:
                already_seen = set()
            join_tuple = tuple([self.query.alias_map[j][TABLE_NAME] for j in joins])
            if join_tuple in already_seen:
                raise FieldError('Infinite loop caused by ordering.')
            already_seen.add(join_tuple)

            results = []
            for item in opts.ordering:
                results.extend(self.find_ordering_name(item, opts, alias,
                        order, already_seen))
            return results

        if alias:
            # We have to do the same "final join" optimisation as in
            # add_filter, since the final column might not otherwise be part of
            # the select set (so we can't order on it).
            while 1:
                join = self.query.alias_map[alias]
                if col != join[RHS_JOIN_COL]:
                    break
                self.query.unref_alias(alias)
                alias = join[LHS_ALIAS]
                col = join[LHS_JOIN_COL]
        return [(alias, col, order)]
    def pre_sql_setup(self):
        """
        Does any necessary class xsetup immediately prior to producing SQL. This
        is for things that can't necessarily be done in __init__ because we
        might not have all the pieces in place at that time.
        """
        if not self.query.tables:
            self.query.join((None, self.query.model._meta.db_table, None, None))
        if (not self.query.select and self.query.default_cols and not
                self.query.included_inherited_models):
            self.query.setup_inherited_models()
        if self.query.select_related and not self.query.related_select_cols:
            self.fill_related_selections()

    def fill_related_selections(self, opts=None, root_alias=None, cur_depth=1,
            used=None, requested=None, restricted=None, nullable=None,
            dupe_set=None, avoid_set=None):
        """
        Fill in the information needed for a select_related query. The current
        depth is measured as the number of connections away from the root model
        (for example, cur_depth=1 means we are looking at models with direct
        connections to the root model).
        """
        if not restricted and self.query.max_depth and cur_depth > self.query.max_depth:
            # We've recursed far enough; bail out.
            return

        if not opts:
            opts = self.query.get_meta()
            root_alias = self.query.get_initial_alias()
            self.query.related_select_cols = []
            self.query.related_select_fields = []
        if not used:
            used = set()
        if dupe_set is None:
            dupe_set = set()
        if avoid_set is None:
            avoid_set = set()
        orig_dupe_set = dupe_set

        # Setup for the case when only particular related fields should be
        # included in the related selection.
        if requested is None:
            if isinstance(self.query.select_related, dict):
                requested = self.query.select_related
                restricted = True
            else:
                restricted = False

        for f, model in opts.get_fields_with_model():
            if not select_related_descend(f, restricted, requested):
                continue
            # The "avoid" set is aliases we want to avoid just for this
            # particular branch of the recursion. They aren't permanently
            # forbidden from reuse in the related selection tables (which is
            # what "used" specifies).
            avoid = avoid_set.copy()
            dupe_set = orig_dupe_set.copy()
            table = f.rel.to._meta.db_table
            promote = nullable or f.null
            if model:
                int_opts = opts
                alias = root_alias
                alias_chain = []
                for int_model in opts.get_base_chain(model):
                    # Proxy model have elements in base chain
                    # with no parents, assign the new options
                    # object and skip to the next base in that
                    # case
                    if not int_opts.parents[int_model]:
                        int_opts = int_model._meta
                        continue
                    lhs_col = int_opts.parents[int_model].column
                    dedupe = lhs_col in opts.duplicate_targets
                    if dedupe:
                        avoid.update(self.query.dupe_avoidance.get((id(opts), lhs_col),
                                ()))
                        dupe_set.add((opts, lhs_col))
                    int_opts = int_model._meta
                    alias = self.query.join((alias, int_opts.db_table, lhs_col,
                            int_opts.pk.column), exclusions=used,
                            promote=promote)
                    alias_chain.append(alias)
                    for (dupe_opts, dupe_col) in dupe_set:
                        self.query.update_dupe_avoidance(dupe_opts, dupe_col, alias)
                if self.query.alias_map[root_alias][JOIN_TYPE] == self.query.LOUTER:
                    self.query.promote_alias_chain(alias_chain, True)
            else:
                alias = root_alias

            dedupe = f.column in opts.duplicate_targets
            if dupe_set or dedupe:
                avoid.update(self.query.dupe_avoidance.get((id(opts), f.column), ()))
                if dedupe:
                    dupe_set.add((opts, f.column))

            alias = self.query.join((alias, table, f.column,
                    f.rel.get_related_field().column),
                    exclusions=used.union(avoid), promote=promote)
            used.add(alias)
            columns, aliases = self.get_default_columns(start_alias=alias,
                    opts=f.rel.to._meta, as_pairs=True)
            self.query.related_select_cols.extend(columns)
            if self.query.alias_map[alias][JOIN_TYPE] == self.query.LOUTER:
                self.query.promote_alias_chain(aliases, True)
            self.query.related_select_fields.extend(f.rel.to._meta.fields)
            if restricted:
                next = requested.get(f.name, {})
            else:
                next = False
            new_nullable = f.null or promote
            for dupe_opts, dupe_col in dupe_set:
                self.query.update_dupe_avoidance(dupe_opts, dupe_col, alias)
            self.fill_related_selections(f.rel.to._meta, alias, cur_depth + 1,
                    used, next, restricted, new_nullable, dupe_set, avoid)

        if restricted:
            related_fields = [
                (o.field, o.model)
                for o in opts.get_all_related_objects()
                if o.field.unique
            ]
            for f, model in related_fields:
                if not select_related_descend(f, restricted, requested, reverse=True):
                    continue
                # The "avoid" set is aliases we want to avoid just for this
                # particular branch of the recursion. They aren't permanently
                # forbidden from reuse in the related selection tables (which is
                # what "used" specifies).
                avoid = avoid_set.copy()
                dupe_set = orig_dupe_set.copy()
                table = model._meta.db_table

                int_opts = opts
                alias = root_alias
                alias_chain = []
                chain = opts.get_base_chain(f.rel.to)
                if chain is not None:
                    for int_model in chain:
                        # Proxy model have elements in base chain
                        # with no parents, assign the new options
                        # object and skip to the next base in that
                        # case
                        if not int_opts.parents[int_model]:
                            int_opts = int_model._meta
                            continue
                        lhs_col = int_opts.parents[int_model].column
                        dedupe = lhs_col in opts.duplicate_targets
                        if dedupe:
                            avoid.update((self.query.dupe_avoidance.get(id(opts), lhs_col),
                                ()))
                            dupe_set.add((opts, lhs_col))
                        int_opts = int_model._meta
                        alias = self.query.join(
                            (alias, int_opts.db_table, lhs_col, int_opts.pk.column),
                            exclusions=used, promote=True, reuse=used
                        )
                        alias_chain.append(alias)
                        for dupe_opts, dupe_col in dupe_set:
                            self.query.update_dupe_avoidance(dupe_opts, dupe_col, alias)
                    dedupe = f.column in opts.duplicate_targets
                    if dupe_set or dedupe:
                        avoid.update(self.query.dupe_avoidance.get((id(opts), f.column), ()))
                        if dedupe:
                            dupe_set.add((opts, f.column))
                alias = self.query.join(
                    (alias, table, f.rel.get_related_field().column, f.column),
                    exclusions=used.union(avoid),
                    promote=True
                )
                used.add(alias)
                columns, aliases = self.get_default_columns(start_alias=alias,
                    opts=model._meta, as_pairs=True, local_only=True)
                self.query.related_select_cols.extend(columns)
                self.query.related_select_fields.extend(model._meta.fields)

                next = requested.get(f.related_query_name(), {})
                new_nullable = f.null or None

                self.fill_related_selections(model._meta, table, cur_depth+1,
                    used, next, restricted, new_nullable)

    def get_default_columns(self, with_aliases=False, col_aliases=None,
            start_alias=None, opts=None, as_pairs=False, local_only=False):
        return [], set()

    def parse_ordering(self):
        result = {}
        group_by_result = {}

        if self.query.extra_order_by:
            raise NotImplementedError
            ordering = self.query.extra_order_by
        elif not self.query.default_ordering:
            ordering = self.query.order_by
        else:
            ordering = self.query.order_by or self.query.model._meta.ordering

        distinct = self.query.distinct

        ordering_aliases = []
        standard_ordering =  self.query.standard_ordering
        
        # It's possible, due to model inheritance, that normal usage might try
        # to include the same field more than once in the ordering. We track
        # the table/column pairs we use and discard any after the first use.
        processed_pairs = set()



        for field in ordering:
            if field == '?':
                raise NotImplementedError
                result.append(self.connection.ops.random_function_sql())
                continue
            if isinstance(field, int):
                raise NotImplementedError
                if field < 0:
                    order = desc
                    field = -field
                else:
                    order = asc
                result.append('%s %s' % (field, order))
                group_by.append((field, []))
                continue
            col, order = get_order_dir(field, standard_ordering)
            if col in self.query.aggregate_select:
                raise NotImplementedError
                result.append('%s %s' % (col, order))
                continue
            if '.' in field:
                raise NotImplementedError
                # This came in through an extra(order_by=...) addition. Pass it
                # on verbatim.
                table, col = col.split('.', 1)
                if (table, col) not in processed_pairs:
                    elt = '%s.%s' % (qn(table), col)
                    processed_pairs.add((table, col))
                    if not distinct or elt in select_aliases:
                        result.append('%s %s' % (elt, order))
                        group_by.append((elt, []))
            elif get_order_dir(field)[0] not in self.query.extra_select:
                # 'col' is of the form 'field' or 'field1__field2' or
                # '-field1__field2__field', etc.
                for table, col, order in self.find_ordering_name(field,
                        self.query.model._meta, default_order=1):

                    if (table, col) not in processed_pairs:
                        result.setdefault( table, [] )
                        result[table].append( (col, order ))
                        group_by_result.setdefault( table, [] )
                        group_by_result[table].append( col )

                        #elt = '%s.%s' % (qn(table), qn2(col))
                        processed_pairs.add((table, col))
                        if distinct :
                            raise NotImplementedError
                            ordering_aliases.append(elt)
                        #result.append('%s %s' % (elt, order))
                        #group_by.append((elt, []))
            else:
                raise NotImplementedError
                elt = qn2(col)
                if distinct and col not in select_aliases:
                    ordering_aliases.append(elt)
                result.append('%s %s' % (elt, order))
                group_by.append(self.query.extra_select[col])
        self.query.ordering_aliases = ordering_aliases
        return result, group_by_result

    def _make_atom(self, child, negated=False ):

        lvalue, lookup_type, value_annot, params_or_value = child
        if hasattr(lvalue, 'process'):
            lvalue, params = lvalue.process(lookup_type, params_or_value, self.connection)
            tbl, col, d_ = lvalue

        else:
            raise NotImplementedError

            params = Field().get_db_prep_lookup(lookup_type, params_or_value,
                                    connection=self.connection, prepared=True)

            
        if hasattr(params, 'as_sql'):
            target, d_ = params.as_sql(lambda s:s, self.connection)
            target = target.replace( tbl, 'this' )
            op = get_op( lookup_type, negated )
            rhs = target % tuple(d_ )
            cond = { '$where' : "this.%s %s %s" % ( col, op, rhs)}
            return tbl , cond

        if params and isinstance(params, dict) and lookup_type == 'exact':
            query = {}
            for k , v in params.items():
                query.update ( { '%s.%s' % (col, k ) : v } )
            return tbl , query
        
        if lookup_type in self.connection.operators:
            
            if negated:
                rhs = self.connection.negated_operators[lookup_type]( params ) 
            else:
                rhs = self.connection.operators[lookup_type]( params ) 

            return tbl , { col : rhs }
        elif lookup_type == 'isnull':
            if negated :
                rhs = params_or_value or None and {'$ne': None }
            else:
                rhs = params_or_value or {'$ne':None} and None
            return tbl , { col : rhs }

        elif lookup_type == 'month':
            if negated:
                cond = { '$where' : "this.%s.getMonth() != %d-1" % ( col, params[0] )}
            else:
                cond = { '$where' : "this.%s.getMonth() == %d-1" % ( col, params[0] )}
            return tbl , cond
        elif lookup_type == 'day':
            if negated:
                cond = { '$where' : "this.%s.getDate() != %d" % ( col, params[0] )}
            else:
                cond = { '$where' : "this.%s.getDate() == %d" % ( col, params[0] )}
            return tbl , cond
        else:
            raise NotImplementedError, 'lookup type %s' % lookup_type


    def parse_where(self, where = None, negated=False):

        if not where:
            where = self.query.where

        result = {}

        if not where.children:
            return result

        for child in where.children:
            if hasattr(child, 'as_sql'):
                sub_result = self.parse_where(child, where.negated )
            else:
                tbl, condition = self._make_atom( child, negated )
                if not tbl:
                    tbl = self.query.tables[0]
                sub_result = { tbl: condition }

            full_update( result, sub_result, where.connector )

        return result

    def as_sql(self, with_limits=True, with_col_aliases=False):
        """
        Creates the SQL for this query. Returns the SQL string and list of
        parameters.

        If 'with_limits' is False, any limit/offset information is not included
        in the query.
        """
        result = {}
        condition = {}
        keyword = {}

        self.pre_sql_setup()
        parsed_out_cols = self.parse_columns()
        #out_cols = []
        #ordering, ordering_group_by = self.get_ordering()

        # This must come after 'select' and 'ordering' -- see docstring of
        # get_from_clause() for details.
        from_, f_params = self.get_from_clause()

        self._join_tables = from_
        self._join_target = f_params

        parsed_where = self.parse_where( )
        parsed_ordering, ordering_group_by  = self.parse_ordering()
        qn = lambda s:s
        having, h_params = self.query.having.as_sql(qn=qn, connection=self.connection)
        params = {}
        for val in self.query.extra_select.itervalues():
            if val[1]:
                raise NotImplementedError
                params.extend(val[1])

        if self.query.distinct:
            keyword['distinct'] = True

        #print 'select as_sql', from_,f_params,out_cols, ordering, ordering_group_by, parsed_where, having,  params

        #parsed_out_cols = parse_out_cols(from_,out_cols)

        self.parsed_out_cols = parsed_out_cols
            
                    
        grouping, gb_params = self.get_grouping()
        if grouping:
            print 'zzz', from_,f_params,parsed_where ,self.query.aggregate_select, 
            print grouping, gb_params
            #raise NotImplementedError, "grouping"
            if parsed_ordering:
                raise NotImplementedError, "grouping and ordering"
                # If the backend can't group by PK (i.e., any database
                # other than MySQL), then any fields mentioned in the
                # ordering clause needs to be in the group by clause.
                if not self.connection.features.allows_group_by_pk:
                    for col, col_params in ordering_group_by:
                        if col not in grouping:
                            grouping.append(str(col))
                            gb_params.extend(col_params)
            else:
                ordering = self.connection.ops.force_no_ordering()
            result.append('GROUP BY %s' % ', '.join(grouping))
            params.extend(gb_params)

        if having:
            raise NotImplementedError, "having"
            result.append('HAVING %s' % having)
            params.extend(h_params)

        #if ordering:
        #    #raise "must implement here" + str(ordering)
        #    #result.append('ORDER BY %s' % ', '.join(ordering))

        #    keyword['sort'] = parse_ordering(from_,ordering)

        if with_limits:
            if self.query.high_mark is not None:
                keyword['limit'] = self.query.high_mark - self.query.low_mark

            if self.query.low_mark:
                if self.query.high_mark is None:
                    val = self.connection.ops.no_limit_value()
                    if val:
                        keyword['limit'] = val
                keyword['skip'] = self.query.low_mark

        join_kw = {}
        result = None 

        self._join_cache = {}
        target_tbl = from_[0]
        new_condition = {}
        new_condition.update( parsed_where.get( target_tbl , {} ))
        for lhs, rhs in f_params.items():
            lhs_tbl, lhs_col = lhs.split('.')
            rhs_tbl, rhs_col = rhs.split('.')
            cursor = self.connection.cursor()
            join_condition = parsed_where.get(rhs_tbl,{})
            fields = parsed_out_cols.get( rhs_tbl, None )  or None
            join_options = { 'fields':fields ,
                            'sort' : parsed_ordering.get(rhs_tbl,None) }

            rows = cursor.find(rhs_tbl, join_condition, join_options )

            join_value = {}
            for r in rows:
                join_value[ r[rhs_col] ] = r
            value_list = join_value.keys()
            self._join_cache[ rhs ] = join_value
            if lhs_tbl == target_tbl:
                full_value_update( new_condition, { lhs_col: {'$in' : value_list } } )
            else:
                raise NotImplementedError

        keyword[ 'sort'] = parsed_ordering.get( target_tbl, None )
        keyword[ 'fields'] = parsed_out_cols.get( target_tbl, None )  or None
        return target_tbl, (new_condition, keyword)


    def execute_sql(self, result_type=MULTI, count=True):
        """
        Run the query against the database and returns the result(s). The
        return value is a single data item if result_type is SINGLE, or an
        iterator over the results if the result_type is MULTI.

        result_type is either MULTI (use fetchmany() to retrieve all rows),
        SINGLE (only retrieve a single row), or None. In this last case, the
        cursor is returned if any query is executed, since it's used by
        subclasses such as InsertQuery). It's possible, however, that no query
        is needed, as the filters describe an empty set. In that case, None is
        returned, to avoid any unnecessary database interaction.
        """
        #try:
        #    table, sql = self.as_sql()
        #    if not sql:
        #        raise EmptyResultSet
        #except EmptyResultSet:
        #    if result_type == MULTI:
        #        return empty_iter()
        #    else:
        #        return
        #self.p()

        count = False


        table, (sql,options) = self.as_sql()
        cursor = self.connection.cursor()

        if self.query.aggregate_select:
            final_result = []
            for aggregate_name, aggregate in self.query.aggregate_select.items():
                cls_name = aggregate.__class__.__name__ 
                if cls_name == 'Count':
                    result = cursor.find(table, sql, options).count()
                else:
                    assert table == aggregate.col[0]
                    result = getattr( cursor, cls_name.lower() )( table, aggregate.col[1], sql, options )

                final_result.append(result)

            return final_result

        if result_type == SINGLE:
            return cursor.find_one(table, sql, options)

        return cursor.find(table, sql, options)


    def parse_columns(self ):
        """
        Returns the list of columns to use in the select statement. If no
        columns have been specified, returns all columns relating to fields in
        the model.

        If 'with_aliases' is true, any column names that are duplicated
        (without the table names) are given unique aliases. This is needed in
        some cases to avoid ambiguity with nested queries.
        """
        #qn = self.quote_name_unless_alias
        #qn2 = self.connection.ops.quote_name
        #print 'get_columns', qn, qn2
        #result = ['(%s) AS %s' % (col[0], qn2(alias)) for alias, col in self.query.extra_select.iteritems()]
        #if self.query.extra_select:
        #    raise str(self.query.extra_select)
        #result = [col[0] for alias, col in self.query.extra_select.iteritems()]

        result = {}
        aliases = set(self.query.extra_select.keys())
        col_aliases = set()

        if self.query.select:
            #only_load = self.deferred_to_columns()
            only_load = {}
            for col in self.query.select:
                if isinstance(col, (list, tuple)):
                    alias, column = col
                    table = self.query.alias_map[alias][TABLE_NAME]
                    if table in only_load and col not in only_load[table]:
                        continue
                    result.setdefault( table, [] )
                    result[ table ].append(column)
                else:
                    result.append(col.as_sql(qn, self.connection))

                    if hasattr(col, 'alias'):
                        aliases.add(col.alias)
                        col_aliases.add(col.alias)

        elif self.query.default_cols:
            cols, new_aliases = self.get_default_columns(col_aliases=col_aliases)
            #cols, new_aliases = [],{}

            table = self.query.tables[0] 
            result.setdefault( table, [] )
            result[ table ].extend(cols)
            aliases.update(new_aliases)

        max_name_length = self.connection.ops.max_name_length()
        #result.extend([
        #    '%s%s' % (
        #        aggregate.as_sql(qn, self.connection),
        #        alias is not None
        #            and ' AS %s' % qn(truncate_name(alias, max_name_length))
        #            or ''
        #    )
        #    for alias, aggregate in self.query.aggregate_select.items()
        #])

        for table, col in self.query.related_select_cols:
            r = '%s.%s' % (qn(table), qn(col))
            if with_aliases and col in col_aliases:
                c_alias = 'Col%d' % len(col_aliases)
                result.append('%s AS %s' % (r, c_alias))
                aliases.add(c_alias)
                col_aliases.add(c_alias)
            else:
                result.append(r)
                aliases.add(r)
                col_aliases.add(col)

        return result

    def resolve_columns(self, row, fields):

        rec = []

        related= {}
        for field in fields:
            name = field.attname 
            if isinstance( field, AutoField ) and name == 'id':
                name = '_id'
            value = row.get( name )

            lhs = '%s.%s' % (field.model._meta.db_table, name)
            if lhs in self._join_target:
                rhs = self._join_target[lhs]
                rhs_tbl, rhs_col = rhs.split('.')
                join_data = self._join_cache[ rhs ]
                join_row = join_data[value]
                join_fields = [ f for f in self.query.related_select_fields if f.model._meta.db_table == rhs_tbl ]
                related.setdefault(rhs_tbl,[])
                related_rec = related[rhs_tbl]
                for field in join_fields:
                    related_rec.append( join_row.get(field.attname,None) )

            value = self.connection.ops.convert_values( value, field )
            rec.append( value )

        for tbl in self._join_tables[1:]:
            rec.extend( related[tbl] )

        return rec
        

    def results_iter(self):
        """
        Returns an iterator over the results from executing this query.
        """
        resolve_columns = hasattr(self, 'resolve_columns')
        fields = None
        for row in self.execute_sql(MULTI):

            if resolve_columns:
                if fields is None:
                    # We only set this up here because
                    # related_select_fields isn't populated until
                    # execute_sql() has been called.
                    if self.query.select_fields:
                        fields = self.query.select_fields + self.query.related_select_fields
                    else:
                        fields = self.query.model._meta.fields
                    # If the field was deferred, exclude it from being passed
                    # into `resolve_columns` because it wasn't selected.
                    #only_load = self.deferred_to_columns()
                    #if only_load:
                    #    db_table = self.query.model._meta.db_table
                    #    fields = [f for f in fields if db_table in only_load and
                    #              f.column in only_load[db_table]]
                row = self.resolve_columns(row, fields)

            if self.query.aggregate_select:
                raise NotImplementedError
                aggregate_start = len(self.query.extra_select.keys()) + len(self.query.select)
                aggregate_end = aggregate_start + len(self.query.aggregate_select)
                row = tuple(row[:aggregate_start]) + tuple([
                    self.query.resolve_aggregate(value, aggregate, self.connection)
                    for (alias, aggregate), value
                    in zip(self.query.aggregate_select.items(), row[aggregate_start:aggregate_end])
                ]) + tuple(row[aggregate_end:])

            yield row

class SQLUpdateCompiler(SQLCompiler):

    def as_sql(self):
        """
        Creates the SQL for this query. Returns the SQL string and list of
        parameters.
        """

        self.pre_sql_setup()
        if not self.query.values:
            return '', ()
        table = self.query.tables[0]
        values = {}
        for field, model, val in self.query.values:
            val = field.clean(val, model)

            if hasattr(val, 'prepare_database_save'):
                val = val.prepare_database_save(field)
            else:
                val = field.get_db_prep_save(val, connection=self.connection)

            # Getting the placeholder for the field.
            if hasattr(field, 'get_placeholder'):
                placeholder = field.get_placeholder(val, self.connection)
            else:
                placeholder = '%s'

            if hasattr(val, 'evaluate'):
                val = SQLEvaluator(val, self.query, allow_joins=False)
            name = field.column

            if hasattr(val, 'as_sql'):
                raise NotImplementedError
                sql, params = val.as_sql(qn, self.connection)
                values.append('%s = %s' % (qn(name), sql))
                update_params.extend(params)
            elif val is not None:
                values[ name ] = val
            else:
                values[ name ] = None
        condition_where = self.parse_where()
        return table, condition_where[table], values

    def execute_sql(self, result_type):
        """
        Execute the specified update. Returns the number of rows affected by
        the primary update query. The "primary update query" is the first
        non-empty query that is executed. Row counts for any subsequent,
        related queries are not available.
        """
        table, sql, options = self.as_sql()

        cursor = self.connection.cursor()
        return cursor.update( table, sql, options )

        rows = cursor and cursor.rowcount or 0
        is_empty = cursor is None
        del cursor
        for query in self.query.get_related_updates():
            raise NotImplementedError
            aux_rows = query.get_compiler(self.using).execute_sql(result_type)
            if is_empty:
                rows = aux_rows
                is_empty = False
        return rows

class SQLInsertCompiler(SQLCompiler):

    def placeholder(self, field, val):
        if field is None:
            # A field value of None means the value is raw.
            return val
        elif hasattr(field, 'get_placeholder'):
            raise NotImplementedError
            # Some fields (e.g. geo fields) need special munging before
            # they can be inserted.
            return field.get_placeholder(val, self.connection)
        else:
            # Return the common case for the placeholder
            return val

    def as_sql(self):
        #print 'InsertQueryCompiler'
        # We don't need quote_name_unless_alias() here, since these are all
        # going to be column names (so we can avoid the extra overhead).
        opts = self.query.model._meta
        values = [self.placeholder(*v) for v in self.query.values]

        result = {}
        for i, val in enumerate(values):
            result [self.query.columns[i]] = val

        return opts.db_table, result

    def execute_sql(self, return_id=False):
        self.return_id = return_id
        table, sql = self.as_sql()

        cursor = self.connection.cursor()
        lastrowid = cursor.insert(table, sql )

        return lastrowid
        if not (return_id and lastrowid):
            return

        return cursor.find_one(table, {'_id':lastrowid} )

class SQLDeleteCompiler(SQLCompiler):


    def execute_sql(self , return_type=None):
        table, (sql, options) = self.as_sql()

        cursor = self.connection.cursor()
        return cursor.delete(table, sql )



